<template>
  <div id="giftActivity" style="width:90%;">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="150px"
    >
      <div style="text-align:right">
        <el-button
          @click="goback()"
          size="mini"
          type="primary"
          style="margin-right:10px"
          >返回
        </el-button>
      </div>

      <el-form-item label="直播计划名称：" prop="planName">
        <el-input
          type="textarea"
          v-model="ruleForm.planName"
          :disabled="disabledFlag"
          placeholder="请输入活动名称"
          maxlength="30"
          show-word-limit
          style="width:250px;"
        ></el-input>
      </el-form-item>
      <el-form-item label="直播时间：" prop="actTimeRange">
        <el-date-picker
          v-model="ruleForm.actTimeRange"
          type="datetimerange"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
          :disabled="disabledFlag"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="报名截止时间" prop="enrollEndTime">
        <el-date-picker
          v-model="ruleForm.enrollEndTime"
          type="datetime"
          placeholder="请选择报名截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="expireTimeOption"
          @change="changebaomin"
          :disabled="disabledFlag"
          style="width:200px;"
        ></el-date-picker>
      </el-form-item>

      <!-- <el-form-item
        label="是否可用优惠卷："
        prop="ifUseCoupon"
      >
        <el-radio
          v-model="ruleForm.ifUseCoupon"
          label="1"
        >是
        </el-radio>
        <el-radio
          v-model="ruleForm.ifUseCoupon"
          label="0"
        >否
        </el-radio>
      </el-form-item> -->

      <el-form-item label="活动商品：" prop="goodsCount">
        <el-button
          type="primary"
          @click="showGoodsDialog()"
          icon="el-icon-plus"
          size="mini"
          style="margin:5px 0 20px 0"
          v-if="!disabledFlag"
          >添加商品
        </el-button>
        <!-- <span style="color:#ff0000">{{isGiftEmpty}}</span> -->
        <!--商品列表-->
        <div id="giftActivityGoodsTable">
          <el-table
            ref="goodsTable"
            :data="goodsDTOS"
            border
            style="width:100%;"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="goodsSeq"
              sortable
              column-key="goodsSeq"
              label="商品编码"
              align="center"
            >
            </el-table-column>

            <el-table-column
              prop="goodsName"
              sortable
              column-key="goodsName"
              label="商品名称"
              align="center"
            >
            </el-table-column>
            <!-- <el-table-column
              prop="goodsTypeName"
              sortable
              label="商品分类"
              align="center"
            ></el-table-column> -->
            <el-table-column
              prop="unitName"
              sortable
              label="计量单位"
              align="center"
            ></el-table-column>
            <el-table-column
              label="审核状态"
              align="center"
              width="150"
              prop="auditStatus"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.auditStatus == '0'">未审核</span>
                <span v-if="scope.row.auditStatus == '1'">审核中</span>
                <span v-if="scope.row.auditStatus == '2'">审核通过</span>
                <span v-if="scope.row.auditStatus == '3'">审核失败</span>
                <span v-if="scope.row.auditStatus == '4'">未提交</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="marketSalePrice"
              sortable
              label="商品市场价格（元）"
              header-align="center"
              align="right"
            >
            </el-table-column>

            <el-table-column
              prop="salePrice"
              sortable
              label="商品直播价格（元）"
              header-align="center"
              align="right"
            >
            </el-table-column>

            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  v-if="!disabledFlag"
                  @click="deleteGoodsItem(scope.row, scope.$index)"
                  type="text"
                  >删除商品
                </el-button>
                <el-button
                  size="mini"
                  v-if="!disabledFlag"
                  @click="showGiftsDialog(scope.row, scope.$index)"
                  type="text"
                  >修改价格
                </el-button>
                <el-button
                  size="mini"
                  v-if="
                    actflag == true &&
                      (scope.row.isDaoFlag == true ||
                        scope.row.auditStatus == '0' ||
                        scope.row.auditStatus == '4')
                  "
                  @click="daoru(scope.row, scope.$index)"
                  type="text"
                  >导入微信商品
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item label="门店范围：">
        <el-radio-group v-model="ruleForm.isAllStore" :disabled="disabledFlag">
          <el-radio-button label="0">通用</el-radio-button>
          <el-radio-button label="1">指定门店</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="适用门店："
        prop="shopList"
        v-if="ruleForm.isAllStore == '1'"
      >
        <el-table
          :data="shopList"
          @selection-change="couponShopChecked"
          border
          v-if="ruleForm.isAllStore == '1'"
          style="font-size: 10px;width:100%;"
          height="300"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="authCode"
            label="授权码"
            width="180"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="storeName"
            label="店铺名称"
            width="180"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="storeOwnerName"
            label="店主姓名"
            width="100"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="storeAddressDetail"
            label="店铺地址"
            header-align="center"
          ></el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button
            type="primary"
            @click="selectShop('couponForm')"
            v-if="!disabledFlag"
            >选择门店
          </el-button>
          <el-button @click="deleteShop('couponForm')" v-if="!disabledFlag"
            >删除门店
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-radio-group
          v-model="ruleForm.publishStatus"
          :disabled="disabledFlag"
        >
          <el-radio-button label="0">不发布</el-radio-button>
          <el-radio-button label="1">发布</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item style="width:100%;text-align:center">
        <el-button @click="resetForm('ruleForm')" v-show="!this.disabledFlag"
          >取 消
        </el-button>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          v-show="!this.disabledFlag"
          :loading="submitLoading"
          :disabled="buttonDisabledFlag"
          >保 存
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 添加活动商品弹窗 -->
    <el-dialog
      title="添加活动商品"
      :visible.sync="insertGoodsDialogVisible"
      width="60%"
    >
      <div>
        <el-form :inline="true" :model="formInline2" class="demo-form-inline">
          <el-row :span="24">
            <el-col :span="24">
              <el-form-item label="商品编码：">
                <el-input
                  v-model="formInline2.goodsSeq"
                  clearable
                  placeholder
                  style="width:200px"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品名称：">
                <el-input
                  v-model="formInline2.goodsName"
                  clearable
                  placeholder
                  style="width:200px"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="search2()"
                  size="mini"
                  icon="el-icon-search"
                  >查询
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="kong2()"
                  size="mini"
                  icon="el-icon-delete"
                  >清空
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="table2">
          <el-table
            ref="table2"
            tooltip-effect="dark"
            style="width: 100%"
            v-loading="loading2"
            :data="chooseGoodsList"
            @selection-change="handleSelectionChange2"
            border
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <el-table-column
              type="selection"
              width="60"
              align="center"
              fixed
              disabled
            ></el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="picUrl"
              label="商品图片"
              align="center"
              width="150"
            >
              <template slot-scope="scope">
                <img
                  :src="scope.row.picUrl"
                  v-if="scope.row.picUrl != '' && scope.row.picUrl != null"
                  width="70"
                  height="50"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="goodsSeq"
              label="商品编码"
              align="center"
              width="150"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="goodsName"
              label="商品名称"
              align="center"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="unitName"
              label="计量单位"
              align="center"
              width="100"
            ></el-table-column>
            <el-table-column
              label="商品描述"
              align="center"
              show-overflow-tooltip
              width="300"
            >
              <template slot-scope="scope">
                <div v-html="scope.row.goodsDescribe"></div>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top:22px;overflow:hidden">
            <el-pagination
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
              :current-page="listQuery2.current"
              :page-size="listQuery2.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total2"
            >
            </el-pagination>
          </div>
          <el-row>
            <el-col :span="24" style="text-align: center;margin-top: 30px">
              <el-button type="info" @click="closeGoodsDialog()" size="mini"
                >取 消
              </el-button>
              <el-button type="primary" @click="insertGoods()" size="mini"
                >确 认
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="选择门店" :visible.sync="dialogVisibleShop" width="65%">
      <el-form :inline="true" :model="formShop" class="search-form-inline">
        大区：
        <el-select v-model="formShop.warzone">
          <el-option value>全部大区</el-option>
          <el-option
            v-for="item in warzoneList"
            :key="item.orgSeq"
            :label="item.orgName"
            :value="item.orgSeq"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="formShop.shopName"
          style="width:200px;"
          placeholder="店铺名称"
        ></el-input>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getShopList(1)"
          >查询
        </el-button>
      </el-form>
      <el-table
        ref="shopTable"
        :data="orgDTOS"
        border
        style="font-size: 10px;width:100%;"
        height="300"
        @selection-change="shopChecked"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="authCode"
          label="授权码"
          width="180"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeName"
          label="店铺名称"
          width="180"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeOwnerName"
          label="店主姓名"
          width="100"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeAddressDetail"
          label="店铺地址"
          header-align="center"
        ></el-table-column>
      </el-table>
      <div class="block" style="margin-top:5px;">
        <el-pagination
          @size-change="handleSizeChange3"
          @current-change="handleCurrentChange3"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQuery.current"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleShop = false">取 消</el-button>
        <el-button type="primary" @click="shopConfirm()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleprice" width="40%">
      <el-form ref="form" :model="formprice">
        <!-- <el-form-item label="价格形式">
          <el-radio-group v-model="formprice.priceType">
            <el-radio :label="1">一口价</el-radio>
            <el-radio :label="2">折扣价</el-radio>

          </el-radio-group>
        </el-form-item> -->

        <el-form-item label="市场价格">
          <el-input
            :disabled="true"
            v-model="formprice.priceshichang"
            style="width:150px;"
            placeholder="价格"
            type="number"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="直播价格">
          <el-input
            v-model="formprice.price"
            style="width:150px;"
            placeholder="价格"
            type="number"
            @blur="getprice(formprice.price)"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <!-- <el-form-item label="折扣价格" v-if="this.formprice.priceType==2" >


            <el-input

              v-model="formprice.price"
            style="width:150px;"
            placeholder="市场价格"
              type="number"

            >
              <template slot="append">元</template>
              </el-input>


            <el-input

              v-model="formprice.priceDiscount"
            style="width:150px;"
            placeholder="价格"
              type="number"

            >
              <template slot="append">折</template>
              </el-input>

                 <el-input

              v-model="formprice.addprice"
            style="width:150px;"
            placeholder="折后价格"
              type="number"

            >
              <template slot="append">元</template>
              </el-input>
        </el-form-item>
         -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleprice = false">取 消</el-button>
        <el-button type="primary" @click="changeprice(formprice.price)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  addPreSaleAct,
  getActInfoById,
  getWarzoneList,
  qryGoodsTypeList,
  queryChooseGoodsList,
  queryStoreInfo,
  storZbPlanList,
  zbPlanGoods,
  zbPlanOrgByOrgSeq,
} from '@/api/liveplan';
import { getmemberrule } from '@/api/membergrade';

const curDateStr = function() {
  var curDate = new Date();
  var year = curDate.getFullYear();
  var month = curDate.getMonth() + 1;
  month = month > 9 ? month : '0' + month;
  var date = curDate.getDate();
  date = date > 9 ? date : '0' + date;
  return year + '-' + month + '-' + date;
};

export default {
  data() {
    return {
      priceindex: '',
      formShop: {
        shopName: '',
        warzone: '',
      },
      formprice: {
        priceType: 1,
        priceshichang: '',
        price: '',
        priceDiscount: '',
        addprice: '',
      },
      warzoneList: [],
      checkList: [],
      memberLevelList: [],
      shopList: [],
      orgDTOS: [],
      memberDTOS: [],
      lsShopList: [],
      lsCouponShopList: [],
      disabledFlag: false,
      buttonDisabledFlag: false,
      actflag: false,
      dialogVisibleprice: false,

      dialogVisibleShop: false,
      insertGoodsDialogVisible: false, //挑选商品弹窗
      typeData: [], //商品类型
      ruleForm: {
        limitQuantity: '1',
        isLimitQuantity: '0',
        uuid: null,
        activityCode: '',
        activityType: '1',
        planName: '',
        beginTime: '',
        endTime: '',
        actTimeRange: [],
        runTimeRange: [curDateStr(), curDateStr()],
        finalPaymentTimeRange: [curDateStr(), curDateStr()],
        enrollEndTime: '',
        ifUseCoupon: '0',
        activityDesc: '',
        isAllStore: '',
        isRelatedGoodsType: '0',
        goodsTypeId: '',
        publishStatus: '0',
        status: '',
        goodsCount: '', //商品数量
      },
      rules: {
        activityType: [
          {
            required: true,
            message: '请选择预售活动类型',
            trigger: 'blur',
          },
        ],
        planName: [
          {
            required: true,
            message: '请输入直播计划名称',
            trigger: 'blur',
          },
        ],
        actTimeRange: [
          {
            required: true,
            message: '请选活动有效期',
            trigger: 'blur',
          },
        ],
        runTimeRange: [
          {
            required: true,
            message: '请选择定金支付有效期',
            trigger: 'blur',
          },
        ],
        finalPaymentTimeRange: [
          {
            required: true,
            message: '请选择尾款支付有效期',
            trigger: 'blur',
          },
        ],

        ifUseCoupon: [
          {
            required: true,
            message: '请选择是否可用优惠券',
            trigger: 'blur',
          },
        ],

        enrollEndTime: [
          {
            required: true,
            message: '请选择报名截止时间',
            trigger: 'blur',
          },
        ],
        memberDTOS: [
          {
            required: false,
            message: '请选择目标会员',
            trigger: 'blur',
          },
        ],
        goodsCount: [
          {
            required: true,
            message: '请添加活动商品',
            trigger: 'blur',
          },
        ],
      },
      loading: true,
      loading2: true,
      loading3: true,
      submitLoading: false,
      total: 0,
      total2: 0,
      total3: 0,
      listQuery: {
        current: 1,
        size: 100,
      },
      listQuery2: {
        current: 1,
        size: 10,
      },
      listQuery3: {
        current: 1,
        size: 10,
      },
      sort: '',
      order: '',
      priceflag: false,
      isDaoFlag: false,
      yuanprice: '',
      goodsDTOS: [], //商品列表
      deleteGoodsArray: [],
      shopdeletelist: [],
      chooseGoodsList: [], //挑选商品列表
      zuishangpinlist: [],
      mendianList: [],
      zuimendianList: [],
      shopListone: [],
      shangpinList: [],
      batchSelGoods: [], //记录挑选多选商品id
      editGoodsListIndex: '', //记录编辑的商品列表序号
      editGoodsId: '', //记录编辑的商品主键
      editActivityGoodsId: '', //记录编辑的活动商品主键
      chooseGiftsList: [], //挑选赠品列表
      batchSelGifts: [], //记录挑选多选赠品id
      formInline2: {
        goodsName: '',
        goodsSeq: '',
        goodsTypeId: '',
      }, //查询2
      formInline3: {
        giftName: '',
        giftCode: '',
        giftType: '',
      }, //查询3
      expireTimeOption: {
        disabledDate(date) {
          //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果当天可选，就不用减8.64e7
        },
      },
    };
  },
  mounted() {
    this.getProductType(); //加载商品分类
    this._getmemberinfo();

    this.disabledFlag = this.$route.params.flag;
    this.actflag = this.$route.params.actflag;

    console.log(this.actflag, '998');
    var v = this.$route.params.edit;
    if (v) {
      this.getActInfoById(v);
      this.getstorZbPlanList(v);
    } else {
      this.loading = false;
      this.ruleForm.isAllStore = '0';
    }
    this.getWarzoneList();
    this.getShopList(1);
  },
  methods: {
    // 数组，属性，属性值
    getprice(v) {
      console.log(v, '777');
    },
    changebaomin(v) {
      console.log(this.ruleForm.actTimeRange, v, '888');
      if (this.ruleForm.actTimeRange[1] < v) {
        this.$message({
          showClose: true,
          message: '报名截止时间不能超出活动时间范围',
          type: 'info',
        });
        this.ruleForm.enrollEndTime = '';
      }
    },
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var type = 0;
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          type = 1;
          break;
        }
      }
      console.log(type, 'type');
      console.log(index, 'index');
      if (type == 1) {
        arr.splice(index, 1);
      }
    },

    getWarzoneList() {
      let data = {};
      getWarzoneList(data).then((res) => {
        this.warzoneList = res.records;
      });
    },

    getShopList(current) {
      let data = {
        size: this.listQuery.size,
        current: current,
        condition: {
          upOrgSeq: this.formShop.warzone,
          storeName: this.formShop.shopName,
        },
        ascs: [],
        descs: [],
      };

      queryStoreInfo(data).then((res) => {
        this.orgDTOS = res.records;
        this.total = res.total;
        // 设置回显
        // this.checkboxInit();
        console.log('shopList', this.shopList);

        for (var i in this.shopList) {
          this.removeByValue(this.orgDTOS, 'uuid', this.shopList[i].orgSeq);
          this.total -= 1;
          this.total = this.total < 0 ? 0 : this.total;
        }
      });
      // }

      this.loading = false;
    },

    shopChecked(row) {
      this.lsShopList = row;
    },
    shopConfirm() {
      // 保存已选择的门店
      for (var i = 0; i < this.lsShopList.length; i++) {
        this.lsShopList[i].uuid = '';
      }
      this.dialogVisibleShop = !this.dialogVisibleShop;
      this.shopList = this.shopList.concat(this.lsShopList);
      console.log(this.shopList, '9909ooo77');
      for (var i in this.lsShopList) {
        this.removeByValue(this.orgDTOS, 'uuid', this.lsShopList[i].uuid);
      }
    },

    selectShop() {
      // 显示选择门店对话框
      this.dialogVisibleShop = !this.dialogVisibleShop;
      // this.getShopList();
      this.lsCouponShopList = this.shopList;
    },
    couponShopChecked(row) {
      this.lsCouponShopList = row;
    },

    deleteShop() {
      // 删除已选择的门店
      console.log(this.lsCouponShopList, '99');

      this.shopdeletelist = this.lsCouponShopList;
      for (var i = 0; i < this.shopdeletelist.length; i++) {
        var item = this.shopdeletelist[i];
        if (item.status == 1) {
          item.status = 0;
        }
      }

      this.orgDTOS = this.orgDTOS.concat(this.lsCouponShopList);
      for (var i in this.lsCouponShopList) {
        this.removeByValue(
          this.shopList,
          'uuid',
          this.lsCouponShopList[i].uuid
        );
      }
    },
    //选择目标会员
    changebox(v) {
      if (this.memberDTOS.indexOf(v) === -1) {
        this.memberDTOS.push(v);
      } else {
        this.memberDTOS.splice(this.memberDTOS.indexOf(v), 1);
      }
    },

    _getmemberinfo() {
      let data = {
        size: 10,
        current: 1,
        condition: {},
        ascs: [],
        descs: [],
      };
      getmemberrule(data).then((res) => {
        this.memberLevelList = [];
        this.memberDTOS = [];
        res.records.forEach((item, i) => {
          let data1 = {
            gradelevelName: item.gradelevelName,
            memberLevelId: item.uuid,
          };
          this.memberLevelList.push(data1);
          this.memberDTOS.push(item.uuid);
        });
        this.memberLevelList = res.records;
      });
    },
    getProductType(v) {
      let data = {};
      qryGoodsTypeList(data).then((res) => {
        this.typeData = res.result;
      });
    },
    //查询活动详细
    getActInfoById(v) {
      let data = {
        planId: v.uuid,
      };
      // 修改，回显值

      getActInfoById(data).then((res) => {
        this.ruleForm.uuid = res.result.uuid;
        this.ruleForm.activityCode = res.result.activityCode;
        // this.ruleForm.activityType = v.activityType.toString();
        this.ruleForm.planName = res.result.planName;
        this.ruleForm.actTimeRange = [
          res.result.beginTime.toString(),
          res.result.endTime.toString(),
        ];
        // this.ruleForm.runTimeRange = [v.depositBeginDate.toString(), v.depositEndDate.toString()];
        // this.ruleForm.finalPaymentTimeRange = [v.balanceBeginDate.toString(), v.balanceEndDate.toString()];
        this.ruleForm.enrollEndTime = res.result.enrollEndTime;
        this.ruleForm.ifUseCoupon = String(res.result.ifUseCoupon);
        this.ruleForm.activityDesc = res.result.activityDesc;
        this.ruleForm.isAllStore = res.result.isAllStore;
        this.ruleForm.shopList = res.result.shopList;
        this.ruleForm.isRelatedGoodsType = res.result.isRelatedGoodsType;
        this.ruleForm.goodsTypeId =
          res.result.goodsTypeId == null ? '' : res.result.goodsTypeId;
        this.ruleForm.publishStatus = res.result.publishStatus;
        this.ruleForm.status = res.result.status;

        this.goodsDTOS = res.result.zbPlanGoods;

        //提交按钮禁用判断
        this.buttonDisabled();

        this.ruleForm.goodsCount =
          this.goodsDTOS.length == 0 ? '' : this.goodsDTOS.length;
      });
    },
    //提交按钮禁用判断
    buttonDisabled() {
      let newSomeArr = this.goodsDTOS.some((item, i) => {
        console.log(item.isDaoFlag, 'oxox');
        return (
          item.auditStatus == '0' || item.auditStatus == '4' || item.isDaoFlag
        );
      });
      if (newSomeArr) {
        this.buttonDisabledFlag = true;
      } else {
        this.buttonDisabledFlag = false;
      }
    },

    getstorZbPlanList(v) {
      let data = {
        size: 100,
        current: 1,
        condition: {
          planId: v.uuid,
          status: 1,
        },
        ascs: [],
        descs: [],
      };

      // 修改，回显值

      storZbPlanList(data).then((res) => {
        this.shopList = res.records;
        this.lsCouponShopList = res.records;
      });
    },
    //删除商品行
    deleteGoodsItem(row, index) {
      console.log(row, '99999');
      //删除页面选择的商品
      if (row.uuid === null || row.uuid === undefined || row.uuid === '') {
        this.goodsDTOS.splice(index, 1);
        this.ruleForm.goodsCount =
          this.goodsDTOS.length == 0 ? '' : this.goodsDTOS.length;
      } else {
        row.status = 0;
        zbPlanGoods(row).then((res) => {
          if (res.code == 1) {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'success',
            });
            this.deleteGoodsArray.push(row);

            for (var i = 0; i < this.deleteGoodsArray.length; i++) {
              var item = this.deleteGoodsArray[i];
              if (item.status == 1) {
                item.status = 0;
              }
            }

            this.goodsDTOS.splice(index, 1);
            this.ruleForm.goodsCount =
              this.goodsDTOS.length == 0 ? '' : this.goodsDTOS.length;
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'error',
            });
          }
        });
      }
      this.buttonDisabled();
    },

    /******商品弹窗方法********/
    //显示挑选商品弹窗
    showGoodsDialog() {
      this.queryChooseGoodsList();
      this.insertGoodsDialogVisible = true;
    },

    //关闭挑选商品弹窗
    closeGoodsDialog() {
      this.insertGoodsDialogVisible = false;
      this.chooseGoodsList = [];
    },
    //挑选商品列表
    queryChooseGoodsList() {
      let includeGoods = [];
      this.goodsDTOS.forEach((item, index) => {
        includeGoods.push(item.goodsId);
      });
      let data = {
        current: this.listQuery2.current,
        size: this.listQuery2.size,
        condition: {
          activityId: this.ruleForm.uuid,
          includeGoods: includeGoods.length == 0 ? null : includeGoods,
          goodsName: this.formInline2.goodsName.trim(),
          goodsSeq: this.formInline2.goodsSeq.trim(),
          goodsTypeId: this.formInline2.goodsTypeId,
        },
        ascs: [],
        descs: [],
      };
      queryChooseGoodsList(data).then((res) => {
        console.log(this.goodsDTOS, '123');
        console.log(res.records, '88877');
        if (this.goodsDTOS.length > 0) {
          for (var i in this.goodsDTOS) {
            this.removeByValue(
              res.records,
              'goodsId',
              this.goodsDTOS[i].goodsId
            );
          }
        }
        this.loading2 = false;

        this.chooseGoodsList = res.records;
        console.log(this.chooseGoodsList, '525');
        console.log(res.records, '454');
        this.total2 = res.total;
      });
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.queryChooseGoodsList();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.queryChooseGoodsList();
    },
    //查询挑选商品
    search2() {
      this.listQuery2.current = 1;
      this.queryChooseGoodsList();
    },
    //重置挑选商品
    kong2() {
      this.formInline2.goodsSeq = '';
      this.formInline2.goodsName = '';
      this.formInline2.goodsTypeId = '';
    },
    //监听选择器
    handleSelectionChange2(val) {
      this.batchSelGoods = val;
    },
    //添加商品
    daoru(v, index) {
      console.log(v, index, '888');
      zbPlanGoods(v).then((res) => {
        if (res.code == 1) {
          this.$message({
            showClose: true,
            message: res.message,
            type: 'success',
          });
          this.goodsDTOS[index].isDaoFlag = false;
          this.goodsDTOS[index].auditStatus = '1';
          this.$set(this.goodsDTOS, index, v);
          this.buttonDisabled();
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: 'error',
          });
        }
      });
    },
    insertGoods() {
      if (this.batchSelGoods.length == 0) {
        this.$message({
          showClose: true,
          message: '请先挑选纳入活动的商品',
          type: 'info',
        });
        return false;
      }
      for (let index = 0; index < this.batchSelGoods.length; index++) {
        let row = this.batchSelGoods[index];
        let newGoods = {
          uuid: '',
          planId: this.ruleForm.uuid,
          goodsId: row.goodsId,
          goodsSeq: row.goodsSeq,
          picUrl: row.picUrl,
          goodsName: row.goodsName,
          goodsTypeName: row.goodsTypeName,
          unitName: row.unitName,
          salePrice: row.salePrice,
          marketSalePrice: row.salePrice,
          auditStatus: '4',
          depositMoney: row.depositMoney,
          status: 1,
          isDaoFlag: true,
          expandMoney: row.expandMoney,
          buyCount: 1,
        };
        this.goodsDTOS.splice(0, 0, newGoods);
        console.log(this.goodsDTOS, '888888');
        this.ruleForm.goodsCount =
          this.goodsDTOS.length == 0 ? '' : this.goodsDTOS.length;
      }

      if (this.ruleForm.uuid) this.buttonDisabledFlag = true;

      this.closeGoodsDialog();
    },
    /******赠品弹窗方法********/
    //显示挑选赠品弹窗
    showGiftsDialog(row, index) {
      console.log(row, index, '9999');
      this.yuanprice = row.salePrice;
      this.dialogVisibleprice = !this.dialogVisibleprice;
      this.formprice.priceshichang = row.marketSalePrice;
      this.formprice.price = row.salePrice;
      this.priceindex = index;
      console.log(this.formprice.price, '9ff999');
    },
    changeprice(v) {
      console.log(this.goodsDTOS, '0000');
      let flag = new RegExp(
        '(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)'
      ).test(v);
      if (v === null || v === undefined || v === '') {
        return;
        this.$message({
          showClose: true,
          message: '填入直播价格不能为空',
          type: 'info',
        });
        this.formprice.price = '';
        return;
      } else if (!flag) {
        this.$message({
          showClose: true,
          message: '填入直播价格格式错误',
          type: 'info',
        });
        this.formprice.price = '';
        return;
      }
      if (this.formprice.price == this.yuanprice) {
        this.priceflag = false;
      } else {
        this.priceflag = true;
        this.goodsDTOS[this.priceindex]['isDaoFlag'] = true;
        console.log(
          this.goodsDTOS[this.priceindex],
          '77',
          this.goodsDTOS[this.priceindex]['isDaoFlag']
        );

        this.buttonDisabledFlag = true;
      }
      console.log(this.priceflag, '9988866');
      this.goodsDTOS[this.priceindex].salePrice = this.formprice.price;
      this.goodsDTOS[
        this.priceindex
      ].marketSalePrice = this.formprice.priceshichang;
      this.dialogVisibleprice = !this.dialogVisibleprice;
    },
    handleSizeChange3(val) {
      this.listQuery.size = val;
      this.getShopList(1);
    },
    handleCurrentChange3(val) {
      this.listQuery.current = val;
      this.getShopList(val);
    },
    //监听选择器2
    handleSelectionChange3(val) {
      this.batchSelGifts = val;
    },
    //返回
    goback() {
      this.$router.go('-1');
    },
    //取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push('liveplan');
    },
    //保存活动
    submitForm(formName) {
      console.log(this.shopList, this.shopdeletelist, '88888');

      this.$refs[formName].validate((valid) => {
        if (valid) {
          // if (this.goodsDTOS == null || this.goodsDTOS.length == 0) {
          //   this.$message({showClose: true, message: "活动商品不能为空", type: "info"});
          //   return;
          // }

          // if (this.memberDTOS == null || this.memberDTOS.length == 0) {
          //   this.$message({showClose: true, message: "请选择目标会员", type: "info"});
          //   return;
          // }else{
          //   this.rules.memberDTOS[0].required = false;
          // }

          if (
            this.ruleForm.actTimeRange != null &&
            this.ruleForm.actTimeRange.length == 2
          ) {
            this.ruleForm.beginTime = this.ruleForm.actTimeRange[0];
            this.ruleForm.endTime = this.ruleForm.actTimeRange[1];
          }

          // if (this.ruleForm.runTimeRange != null && this.ruleForm.runTimeRange.length == 2) {
          //   this.ruleForm.depositBeginDate = this.ruleForm.runTimeRange[0];
          //   this.ruleForm.depositEndDate = this.ruleForm.runTimeRange[1];
          // }

          // if (this.ruleForm.finalPaymentTimeRange != null && this.ruleForm.finalPaymentTimeRange.length == 2) {
          //   this.ruleForm.balanceBeginDate = this.ruleForm.finalPaymentTimeRange[0];
          //   this.ruleForm.balanceEndDate = this.ruleForm.finalPaymentTimeRange[1];
          // }
          // if (this.ruleForm.enrollEndTime == "" || this.ruleForm.enrollEndTime == null) {
          //   this.$message.error("请输入报名截止时间");
          //   return;
          // }
          // if (this.ruleForm.isAppoint != '0' && this.ruleForm.isAppoint != '1') {
          //   this.$message.error("请选择门店范围");
          //   return;
          // }
          // if (
          //   this.ruleForm.isAppoint == "1" &&
          //   (this.shopList == null ||
          //     this.shopList.length == 0)
          // ) {
          //   this.$message.error("请选择门店");
          //   return;
          // }
          this.shopList.forEach((item, index) => {
            this.shopListone.push(item.orgSeq);
          });
          let data = {
            uuid: this.ruleForm.uuid,
            //   activityType: this.ruleForm.activityType,
            planName: this.ruleForm.planName,
            beginTime: this.ruleForm.beginTime,
            endTime: this.ruleForm.endTime,
            status: 1,
            //   depositBeginDate: this.ruleForm.depositBeginDate,
            //   depositEndDate: this.ruleForm.depositEndDate,
            //   balanceBeginDate: this.ruleForm.balanceBeginDate,
            //   balanceEndDate: this.ruleForm.balanceEndDate,
            enrollEndTime: this.ruleForm.enrollEndTime,
            //   activityDesc: this.ruleForm.activityDesc,
            ifUseCoupon: this.ruleForm.ifUseCoupon,
            isAllStore: this.ruleForm.isAllStore,
            //   isRelatedGoodsType: this.ruleForm.isRelatedGoodsType,
            //   goodsTypeId: this.ruleForm.goodsTypeId,
            publishStatus: this.ruleForm.publishStatus,
            zbPlanGoods: this.goodsDTOS,

            orgSeqList: this.shopListone,
          };
          this.submitLoading = true;
          if (this.actflag == true) {
            addPreSaleAct(data).then((res) => {
              if (res.code == 1) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                //this.submitLoading = false;
                this.$router.push('liveplan');
              } else {
                this.submitLoading = false;
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              }
            });
          } else {
            //修改

            // this.editshoplist();
            this.editmendianlist();
            addPreSaleAct(data).then((res) => {
              if (res.code == 1) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                //this.submitLoading = false;
                this.$router.push('liveplan');
              } else {
                this.submitLoading = false;
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              }
            });
          }
        } else {
        }
      });
    },
    editmendianlist() {
      this.mendianList = [];
      this.zuimendianlist = [];
      this.mendianList = this.shopList.concat(this.shopdeletelist);

      for (let index = 0; index < this.mendianList.length; index++) {
        let row = this.mendianList[index];
        let newGoods = {
          uuid: row.uuid,
          planId: this.ruleForm.uuid,

          orgSeq: row.orgSeq,

          status: row.status,
        };
        this.zuimendianlist.push(newGoods);
      }
      console.log(this.mendianList, this.zuimendianlist, '9989');
      zbPlanOrgByOrgSeq(this.zuimendianlist).then((res) => {
        if (res.code == 1) {
          // this.$message({
          //   showClose: true,
          //   message: res.message,
          //   type: "success"
          // });
        } else {
          this.submitLoading = false;
          // this.$message({
          //   showClose: true,
          //   message: res.message,
          //   type: "error"
          // });
        }
      });
    },

    editshoplist() {
      this.shangpinList = [];
      this.zuishangpinlist = [];
      this.shangpinList = this.goodsDTOS.concat(this.deleteGoodsArray);

      for (let index = 0; index < this.shangpinList.length; index++) {
        let row = this.shangpinList[index];
        let newGoods = {
          uuid: row.uuid,
          planId: this.ruleForm.uuid,
          goodsId: row.goodsId,
          goodsName: row.goodsName,
          goodsSeq: row.goodsSeq,

          unitName: row.unitName,
          salePrice: row.salePrice,

          status: row.status,
          priceType: row.priceType,
          priceDiscount: row.priceDiscount,
        };
        this.zuishangpinlist.push(newGoods);
      }
      console.log(this.shangpinList, this.zuishangpinlist, '9989');
      zbPlanGoods(this.zuishangpinlist).then((res) => {
        if (res.code == 1) {
          // this.$message({
          //   showClose: true,
          //   message: res.message,
          //   type: "success"
          // });
        } else {
          this.submitLoading = false;
          // this.$message({
          //   showClose: true,
          //   message: res.message,
          //   type: "error"
          // });
        }
      });
    },

    //修改是否关联商品类型
    changeIsRelatedGoodsType() {
      if (this.ruleForm.isRelatedGoodsType == 0) {
        this.ruleForm.goodsTypeId = null;
      }
    },
    //修改赠品数量选择
    changeIsLimitQuantity(row, index, prow, pindex) {
      if (row.isLimitQuantity == 0) {
        //不限
        this.goodsDTOS[pindex].limitQuantity = null;
      } else if (
        row.limitQuantity === null ||
        row.limitQuantity === undefined ||
        row.limitQuantity === ''
      ) {
        this.goodsDTOS[pindex].limitQuantity = 1;
      }
    },
  }, //其他
};
</script>
<style scoped>
#giftActivity /deep/ .giftTable table th,
#giftActivity .giftTable table td {
  border: 1px solid #ebeef5;
}

#giftActivity /deep/ .giftTable table th {
  background: #eef1f6;
  color: #606266;
}

#giftActivity
  /deep/
  .giftTable
  table
  .el-radio-button-inner-child
  .el-radio-button__inner {
  padding: 0;
}

#giftActivity
  /deep/
  .giftTable
  table
  .el-radio-button-inner-child
  .el-input__inner {
  border: none;
  height: 30px;
}

#giftActivity /deep/ .el-dialog__body {
  padding-top: 0px;
}

#giftActivityGoodsTable /deep/ .el-input__inner[type='number'] {
  padding: 0;
}
</style>
